package com.lyf.boot.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lyf.boot.constant.DbTableConstant;
import com.lyf.boot.core.model.BaseEntity;
import com.lyf.boot.core.model.LoginUser;
import com.lyf.boot.exception.ServiceException;
import com.lyf.boot.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author Luyufan
 * @date 2023/7/3 15:06
 */
@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                LocalDateTime current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
                        ? baseEntity.getCreateTime() : LocalDateTime.now();
                baseEntity.setCreateTime(current);
                baseEntity.setUpdateTime(current);
                baseEntity.setDelFlag(DbTableConstant.NOT_DELETE_FIELD_VALUE);
                Long userId = null != baseEntity.getCreateBy()
                        ? baseEntity.getCreateBy() : getLoginUserId();
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreateBy(userId);
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdateBy(userId);
            }
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "自动注入异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                LocalDateTime current = LocalDateTime.now();
                // 更新时间填充(不管为不为空)
                baseEntity.setUpdateTime(current);
                Long userId = getLoginUserId();
                // 当前已登录 更新人填充(不管为不为空)
                if (null != userId) {
                    baseEntity.setUpdateBy(userId);
                }
            }
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "自动注入异常 => " + e.getMessage());
        }
    }

    /**
     * 获取登录用户名
     */
    private Long getLoginUserId() {
        LoginUser loginUser;
        try {
            loginUser = AuthUtil.getLoginUser();
        } catch (Exception e) {
            //log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return ObjectUtil.isNotNull(loginUser) ? loginUser.getUserId() : null;
    }
}
